package com.ch.android.lookforkotlinv2.vm

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.ch.android.lookforkotlinv2.R
import com.ch.android.networklib.RequestClient
import com.ch.android.networklib.data.API_STATUS_OK
import com.ch.android.networklib.data.BaseResultData
import com.ch.android.networklib.data.LiveTypeData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception

/**
 * Author: conghao
 * Date: 2024/1/19 13:00
 * Description: SquareModel
 */
class SquareModel(application: Application) : AndroidViewModel(application) {
    val liveTypes = MutableLiveData<MutableList<LiveTypeData>>()
    val error = MutableLiveData<Throwable>()

    fun loadData() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val baseResult = RequestClient.getApiService(getApplication()).getLiveTypeList()
                if (baseResult.status== API_STATUS_OK) {
                    val types = baseResult.result ?: mutableListOf()
                    val strQuanBu = this@SquareModel.getApplication<Application>().getString(R.string.quan_bu)
                    types.add(LiveTypeData(id = 100, name = strQuanBu, rank = 0))
                    //按rank值，从小到大排序
                    types.sortBy { it.rank }
                    withContext(Dispatchers.Main) {
                        liveTypes.value = types
                    }
                } else {
                    withContext(Dispatchers.Main) {
                        error.value = Exception(baseResult.message)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    error.value = e
                }
            }
        }
    }
}